package com.bbcare.mqservice.controller;


import com.bbcare.mqservice.entity.Message;
import com.bbcare.mqservice.pojo.ResultModel;
import com.bbcare.mqservice.service.IMessageService;
import com.bbcare.mqservice.utils.IpUtils;
import com.bbcare.mqservice.utils.rockermq.MqttProducerService;
import com.bbcare.mqservice.utils.rockermq.RocketmqProducerService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;


@Controller
@RequestMapping("/mqservice")
public class mqServiceController {
    private static  final Logger log = LogManager.getLogger();

    @Value("${aliyun.mq.send.msgTopic}")
    private String mqSendTopic;

    @Autowired
    private RocketmqProducerService rocketmqProducerService;

    @Autowired
    private MqttProducerService mqttProducerService;

    @Autowired
    private IMessageService iMessageService;
    @ResponseBody
    @RequestMapping(value="mqtt")
    public ResultModel getMqtt(@RequestBody String requestBody, HttpServletRequest request) throws MqttException {
        log.info("mqtt-->" +requestBody);
        Message message = new Message();
        message.setOriIp(IpUtils.getIpAddr(request));
        message.setCreatTime(LocalDateTime.now());
        message.setMessage(requestBody);
        message.setType("发送");
        //String status =   rocketmqProducerService.sendMsg(mqSendTopic,requestBody);
        boolean status = mqttProducerService.publish(requestBody);
        message.setResult(Boolean.toString(status));
        message.setEndTime(LocalDateTime.now());
        iMessageService.save(message);
        return new ResultModel<Object>(status);
    }

    @ResponseBody
    @RequestMapping(value="rocketmq")
    public ResultModel getRocketmq(@RequestBody String requestBody,HttpServletRequest request){
        //TODO 目前没有作用
        log.info("-->" +requestBody);
        Message message = new Message();
        message.setOriIp(IpUtils.getIpAddr(request));
        message.setCreatTime(LocalDateTime.now());
        message.setMessage(requestBody);
        message.setType("rocketmq");
        String status =  rocketmqProducerService.sendMsg(mqSendTopic,requestBody);
        message.setResult(status);
        message.setEndTime(LocalDateTime.now());
        iMessageService.save(message);
        return new ResultModel<Object>(status);
    }


}
